# algorithm/models/tag_dependency.py
from django.db import models
from tag.models import AlgorithmTag
from django.core.exceptions import ObjectDoesNotExist
import logging
logger = logging.getLogger('algorithm')


# logger.info(f"Starting complex_algorithm_function with param: {param}")
# logger.info(f"Finished complex_algorithm_function with result: {result}")
class TagDependency(models.Model):
    source_tag = models.ForeignKey(AlgorithmTag, related_name='outgoing_edges', on_delete=models.CASCADE)
    target_tag = models.ForeignKey(AlgorithmTag, related_name='incoming_edges', on_delete=models.CASCADE)
    weight = models.FloatField(default=1.0)

    def __str__(self):
        return f"{self.source_tag.tag_name} -> {self.target_tag.tag_name} (Weight: {self.weight})"

    class Meta:
        unique_together = ('source_tag', 'target_tag')  # 设为复合主键

    @classmethod
    def create_or_update(cls, source_tag_index, target_tag_index, weight=1.0):
        try:

            # logger.info(f"{cls.__name__}.create_or_update - begin")

            # 获取 source_tag 和 target_tag
            source_tag = AlgorithmTag.objects.get(index=source_tag_index)
            target_tag = AlgorithmTag.objects.get(index=target_tag_index)

            # 创建或更新 TagDependency
            tag_dependency, created = cls.objects.update_or_create(
                source_tag=source_tag,
                target_tag=target_tag,
                defaults={'weight': weight}
            )

            if created:
                print(f"Created new dependency: {source_tag.tag_name} -> {target_tag.tag_name} with weight {weight}")
                logger.info(f"{cls.__name__}.create_or_update:Created new dependency: {source_tag.tag_name} -> {target_tag.tag_name} with weight {weight}")
            else:
                print(
                    f"Updated existing dependency: {source_tag.tag_name} -> {target_tag.tag_name} with weight {weight}")
                logger.info(f"{cls.__name__}.create_or_update:Updated existing dependency: {source_tag.tag_name} -> {target_tag.tag_name} with weight {weight}")

            return tag_dependency, created

        except ObjectDoesNotExist:
            print(f"Tag with index {source_tag_index} or {target_tag_index} does not exist.")
            logger.error(f"{cls.__name__}.create_or_update:Tag with index {source_tag_index} or {target_tag_index} does not exist.")
            return None, False

    # 清除所有的依赖关系
    @classmethod
    def clear_all_dependencies(cls):
        logger.info(f"{cls.__name__}.clear_all_dependencies")
        cls.objects.all().delete()  # 删除所有 TagDependency 实例
        print("All dependencies have been cleared.")

    # 打印数据库中所有的依赖关系
    @classmethod
    def print_all_dependencies(cls):
        logger.info(f"{cls.__name__}.print_all_dependencies")
        dependencies = cls.objects.all()
        if dependencies.exists():
            print("All Tag Dependencies:")
            for dependency in dependencies:
                print(
                    f"{dependency.source_tag.tag_name} -> {dependency.target_tag.tag_name} (Weight: {dependency.weight})")
        else:
            print("No dependencies found.")

    @classmethod
    def delete_dependency(cls, source_tag_index, target_tag_index):
        # 删除指定的依赖关系
        try:
            source_tag = AlgorithmTag.objects.get(index=source_tag_index)
            target_tag = AlgorithmTag.objects.get(index=target_tag_index)

            # 尝试删除该依赖关系
            dependency = cls.objects.get(source_tag=source_tag, target_tag=target_tag)
            dependency.delete()

            print(f"Deleted dependency: {source_tag.tag_name} -> {target_tag.tag_name}")
            logger.info(f"Deleted dependency: {source_tag.tag_name} -> {target_tag.tag_name}")

        except cls.DoesNotExist:
            print(f"No dependency found between {source_tag_index} and {target_tag_index}.")
            logger.error(f"{cls.__name__}.delete_dependency : No dependency found between {source_tag_index} and {target_tag_index}.")
        except AlgorithmTag.DoesNotExist:
            print(f"Tag with index {source_tag_index} or {target_tag_index} does not exist.")
            logger.error(f"{cls.__name__}.delete_dependency : Tag with index {source_tag_index} or {target_tag_index} does not exist.")
